package com.ntlg.shirospringboot.config;

import com.ntlg.shirospringboot.admin.Shiro;
import com.ntlg.shirospringboot.service.ShiroService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {
    @Autowired
    ShiroService shiroService;
    /*授权操作*/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        /*获取用户*/
        Subject subject = SecurityUtils.getSubject();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
       Shiro shiro =(Shiro) subject.getPrincipal();
       info.addStringPermission(shiro.getPerms());
        return info;
    }

    /*认证操作*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        Shiro shiro = shiroService.selectAll(userToken.getUsername());
        /*验证用户名*/
        if (shiro==null){
             return null;
        }
          /*验证密码*/
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(shiro, shiro.getPassword(), "");
        return  simpleAuthenticationInfo;
    }
}
